from flask_restx import Resource, Namespace,fields
from flask import request,g
import json
api_ns = Namespace('user', description='用户相关')

UserBase = api_ns.model('UserBase', {
    'username': fields.String(description='用户名称'),
    'id': fields.Integer(description='用户id'),
    'age': fields.Integer(description='用户年龄')
})

UserParams = api_ns.model('UserParams', {
    'data': fields.Nested(UserBase,description="用户信息"),
    'code': fields.Integer(description='状态码'),
    'msg': fields.String(description='请求结果')
})

@api_ns.route('/getUser')
@api_ns.doc(params={'id': {'type': int,'description':'必传：用户id','required':True}})
class User(Resource):
    '''Show a single User item and lets you delete them'''
    @api_ns.marshal_with(UserParams)
    def get(self):
        '''根据id查找用户'''
        db = g.db
        id = request.args.get("id",type=int) or 0
        try:
          cursor = db.cursor()
          sql = 'SELECT * from USER WHERE id = %s'
          cursor.execute(sql,id)
          # 只在查询的时候使用 fetchone查询一条 fetchall查全部
          result = cursor.fetchone()
          return {'code':200,'data':result,'msg':'success'}
        except:
            return {'code':500,'data':"系统异常",'msg':'success'}
        finally:
            cursor.close()
            
@api_ns.route("/addUser")
@api_ns.doc()
class AddUser(Resource):
    @api_ns.marshal_with(UserParams)
    def get(self):
        """添加一条用户记录"""
        db = g.db
        try:
          cursor = db.cursor()
          sql = 'INSERT INTO USER VALUES (NULL,"赵老六",30)'
          cursor.execute(sql)
          db.commit()
          return {'code':200,'data':cursor.lastrowid,'msg':'success'}
        except:
            db.rollback()
            return {'code':500,'data':"系统异常",'msg':'success'}
        finally:
            cursor.close()
    